var jvAdmin, rootLayout, jvDragging = false;

Element.extend({
    getParentByClass: function(cls){
        var target = this;
        while (target && !$(target).hasClass(cls)) target = target.parentNode;
        return $(target) || false;
    }    
});

/*
Script: 	
	JVXMLParser - JV XML Parser

License:
	Proprietary - JoomlaVi Club members only

Copyright:
	Copyright (C) JoomlaVi. All rights reserved.
*/
var JVXMLParser = {
		
	rootFromString: function(string){
		var root;
		if(window.ie){
			root = new ActiveXObject('Microsoft.XMLDOM');
			root.async = false;
			root.loadXML(string);
		} 
        else{
			root = new DOMParser().parseFromString(string, 'text/xml');
		}
		return root;
	},
	
	rootToHashes: function(root){
		var hashes = [];
		var children = root.childNodes;
		for(var i = 0, l = children.length; i < l; i++){
			var hash = JVXMLParser.nodeToHash(children[i]);
			if(hash){
				hashes.push(hash);
			}
		}
		return hashes;
	},
	
	nodeToHash: function(node){
		switch($type(node)){
			case 'element':
				var attributes = node.attributes;
				var attributesLength = attributes.length;
				var attributesHash = {};
				for(var j = 0; j < attributesLength; j++){
					var attribute = attributes[j];
					if(attribute.nodeValue && attribute.nodeValue != 'inherit') attributesHash[attribute.nodeName] = attribute.nodeValue;
				}
				return {tag: node.nodeName.toLowerCase(), attributes: attributesHash, children: JVXMLParser.rootToHashes(node)};
			case 'textnode': return {text: node.nodeValue};
			default: return null;
		}
	},
		
	hashToHTML: function(hash, level){
		var tabs = new Array(level || 0).join('\t');
		if(hash.text){
			return tabs + hash.text;
		}
		var attributes = [''];
		for(var p in hash.attributes){
			attributes.push(p + '="' + hash.attributes[p] + '"');
		}
		attributes = attributes.join(' ');
		var open = tabs + '<' + hash.tag + attributes + '>\n';
		var close = '\n' + tabs + '</' + hash.tag + '>';
		var children = JVXMLParser.hashesToHTML(hash.children, level + 1);	
		if(!children.length){
			return open + tabs + '</' + hash.tag + '>'
		}		
		return open + children + close;
	},

	hashesToHTML: function(hashes, level){
		var html = [];
		for(var i = 0, l = hashes.length; i < l; i++){
			html.push(JVXMLParser.hashToHTML(hashes[i], level));		
		}
		return html.join('\n');
	}
};

/*
Script: 	
	JVAdmin - JV Administrator site

License:
	Proprietary - JoomlaVi Club members only

Copyright:
	Copyright (C) JoomlaVi. All rights reserved.
*/

var JVAdmin = new Class({

    initialize: function(){
        this.initTab();
		this.initDragDrop();	
    },
    initTab: function(){
        var that = this;
		var jvSliders = $$('.jv-slider');
		var jvSliderContents = $$('.jv-slider-content');
        var paramlist = $$('.paramlist');
		if(!paramlist.length) return;
		var slider = new Element('div', {        
            'class': 'slider-parents'       
        });
		
		var logo = new Element('div', {        
            'class': 'jvlogo'     
        });
		
		var span1 = new Element('span', {        
            'class': 'tl'    
        });
		
		var span2 = new Element('span', {        
            'class': 'tr'    
        });
		
		slider.adopt(span1);
		slider.adopt(span2);		
        slider.adopt(logo);
        
        slider.injectBefore(paramlist[0]);
		
		if(!jvSliders.length || jvSliders.length != jvSliderContents.length) return;
		
		var jvTab = Cookie.get('jvtab');
		if(!jvTab) jvTab = 0;
		jvSliderContents.each(function(jvSliderContent, index){
			if(jvTab != index){
				jvSliderContent.addClass('hidden');
			}
            else{
                that.initSubTab(jvSliderContents[index], index);
            }
		});	
		jvSliders.each(function(jvSlider, index){
			if(index == jvTab) {
				jvSlider.addClass('active');				
			}
			slider.adopt(jvSlider);
			jvSlider.addEvent('click', function(){
				Cookie.set('jvtab', index);
				jvSliders.removeClass('active');
				jvSlider.addClass('active');
				jvSliderContents.each(function(jvsc){
					jvsc.addClass('hidden');					
				});				
				jvSliderContents[index].removeClass('hidden');
                that.initSubTab(jvSliderContents[index], index);
			});
		});	
		
		var paramslogotype = $('paramslogotype');
		var paramslogotypeimage = $('paramslogotype-image');
		var paramslogotypetext = $('paramslogotype-text');
		if(paramslogotype && paramslogotypeimage && paramslogotypetext){
			paramslogotype.addEvent('change', function(){
				if(paramslogotype.options[paramslogotype.selectedIndex].value == 'image'){
					paramslogotypeimage.getParent().removeClass('hidden');
					paramslogotypetext.getParent().addClass('hidden');
				}
				else{
					paramslogotypeimage.getParent().addClass('hidden');
					paramslogotypetext.getParent().removeClass('hidden');
				}
			});
			paramslogotype.fireEvent('change');
		}		
    },
    initSubTab: function(parentTab, parentIndex){
        if(parentTab.inited == true) return;    
		var jvSliders = $(parentTab).getElements('.jv-slider-sub');
		var jvSliderContents = $(parentTab).getElements('.jv-slider-content-sub');
		if(jvSliders.length != jvSliderContents.length) return;
		
		var paramlist = $(parentTab).getFirst();
        
        var slider = new Element('div', {        
            'class': 'slider'      
        });
        
        slider.injectBefore(paramlist);
        
		var jvTab = Cookie.get('jvtabsub' + parentIndex);
		if(!jvTab) jvTab = 0; 
		jvSliderContents.each(function(jvSliderContent, index){
			if(jvTab != index){
				jvSliderContent.addClass('hidden');
			}
		});	
		jvSliders.each(function(jvSlider, index){
			if(index == jvTab) {
				jvSlider.addClass('active');				
			}
			slider.adopt(jvSlider);
			jvSlider.addEvent('click', function(){
				Cookie.set('jvtabsub' + parentIndex, index);
				jvSliders.removeClass('active');
				jvSlider.addClass('active');
				jvSliderContents.each(function(jvsc){
					jvsc.addClass('hidden');					
				});				
				jvSliderContents[index].removeClass('hidden');
			});
		});	
        parentTab.inited = true;
    },
    initDragDrop: function(){
		var that = this;
		var paramslayoutsetting = $('paramslayoutsetting');
		if(!paramslayoutsetting) return;
	    paramslayoutsetting = paramslayoutsetting.value.trim();
        if(paramslayoutsetting == ''){
            paramslayoutsetting = '<layout></layout>';
        }   
		var xmlParsedString = JVXMLParser.rootFromString(paramslayoutsetting);
		rootLayout = JVXMLParser.rootToHashes(xmlParsedString);
		$$('.position, .position-handler, .block, .block-handler').each(function(item, idx){ 
			item.removeEvents();
		});
		$$('.position-handler').each(function(item, idx){ 			
			item.addEvent('mousedown', function(e) {
				if(jvDragging) return;
				jvDragging = true;	
				e = new Event(e).stop();
				var clone = this.getParent().getParent().clone(true)
					.removeClass('position')
					.addClass('ghost')
					.setStyles(this.getParent().getParent().getCoordinates())
					.setStyles({'position': 'absolute'})
					.addEvent('emptydrop', function() {						
						try{
							clone.pr.removeClass('draghover');								
							clone.ps.replaceWith(clone.pr);
							if(clone.pr.getParent().hasClass('modulebox')){
								var positions = clone.pr.getParent().getElements('.position').filter(function(item){return !item.hasClass('position-placeholder')});
								var percent = (100 / positions.length) + '%';
								for(var i = 0, len =  positions.length; i < len; i++){
									positions[i].setStyle('width', percent).addClass('box');
								}
							}
							else{
								clone.pr.setProperty('class', '').addClass('position').setStyle('width', '');
							}
							var retCoord = clone.pr.getCoordinates();
							new Fx.Styles(clone, {
								duration: 500,							
								transition: Fx.Transitions.Quint.easeOut,
								wait: false,
								onComplete: function(){
									clone.remove();	
									jvDragging = false;		
								}
							}).start({top:retCoord.top, left:retCoord.left});
						}catch(ex){}
					}).inject(document.body);	
				clone.pr = this.getParent().getParent();				
				clone.ps = new Element('span', {'class': 'placeholder'}).inject(clone.pr, 'before');
				var drag = clone.makeDraggable({
					droppables: $$('.position')		
				});	
				drag.start(e);				
			});							
		});
		$$('.block-handler').each(function(item, idx){ 			
			item.addEvent('mousedown', function(e) {
				if(jvDragging) return;
				jvDragging = true;
				e = new Event(e).stop();					
				var clone = this.getParent().getParent().clone(true)
					.removeClass('block')
					.addClass('ghost')
					.setStyles(this.getParent().getParent().getCoordinates())
					.setStyles({'position': 'absolute'})
					.addEvent('emptydrop', function() {
						try{
							clone.pr.removeClass('draghover');
							clone.ps.replaceWith(clone.pr);						
							var retCoord = clone.pr.getCoordinates();
							new Fx.Styles(clone, {
								duration: 500,							
								transition: Fx.Transitions.Quint.easeOut,
								wait: false,
								onComplete: function(){
									clone.remove();
									jvDragging = false;		
								}
							}).start({top:retCoord.top, left:retCoord.left});
						}catch(ex){}
					}).inject(document.body);		 				
				clone.pr = this.getParent().getParent();						
				clone.ps = new Element('span', {'class': 'placeholder'}).inject(clone.pr, 'before');					
				var drag = clone.makeDraggable({
					droppables: $$('.block')				
				});	
				drag.start(e);
			});							
		});
		function addPositionDropEvents(drop){
			drop.addEvents({
				'over': function(el, obj){
					if(this.getParent().hasClass('modulebox')){
						el.pr.addClass('box');
					}
					else{
						el.pr.setProperty('class', '').addClass('position').setStyle('width', '');
					}					
					if(el.pr.getParent().hasClass('modulebox')){
						var positions = el.pr.getParent().getElements('.position');
						var percent = (100 / (positions.length -1)) + '%';
						for(var i = 0, len =  positions.length; i < len; i++){
							if(positions[i] != el.pr){
								positions[i].setStyle('width', percent);
							}
						}
					}										
					el.pr.inject(this, this.getPrevious().hasClass('position') ? 'after' : 'before');	
					el.pr.addClass('draghover');
					if(this.getParent().hasClass('modulebox')){
						var positions = this.getParent().getElements('.position').filter(function(item){return !item.hasClass('position-placeholder')});
						var percent = (100 / positions.length) + '%';
						for(var i = 0, len =  positions.length; i < len; i++){
							positions[i].setStyle('width', percent);
						}
					}
				},
				'drop': function(el, obj){
					var blockObj = this.getParent();
					if(!el.ps.getParent().getElements('.position').length){
						addPositionDropEvents(el.ps.replaceWith(el.pr.clone(true).removeProperty('id').removeProperty('name').setHTML('[empty block]').setProperty('class', '').addClass('position').addClass('position-placeholder').setStyle('width', '')));
					}
					else{
						el.ps.remove();
					}
					if(el.pr.getParent().getElement('.position-placeholder')){
						el.pr.getParent().getElement('.position-placeholder').remove();
					}
					el.pr.removeClass('draghover');					
					var positionName = el.pr.id.replace('p-', '');
					var blockName = el.pr.getProperty('name');					
					var blockNameTo = blockObj.id.replace('b-', '');					
					var blockExist = null, positionExist = null, positionIndex = 0;
					rootLayout[0].children.each(function(blockChild){
						var childAttr = blockChild.attributes;						
						if(blockName.toLowerCase() == childAttr.name.toLowerCase()){
							blockExist = blockChild;																
						}
					});
					if(blockExist){
						blockExist.children.each(function(positionChild, positionChildIdx){
							var childAttr = positionChild.attributes;
							if(positionName.toLowerCase() == childAttr.name.toLowerCase()){
								positionExist = positionChild;
								positionIndex = positionChildIdx;								
							}
						});
						if(positionExist){							
							var positionLen = blockObj.getElements('.position').length;
							blockObj.getElements('.position').each(function(tmpItem, tmpIndex){
								if(tmpItem.id.replace('p-', '').toLowerCase() == positionName.toLowerCase()){
									if(tmpIndex == 0){
										positionExist.attributes.where = '';
									}
									else if(tmpIndex == positionLen - 1){
										delete positionExist.attributes.where;
									}
									else{
										positionExist.attributes.where = tmpItem.getPrevious().id.replace('p-', '');
									}										
								}									
							});	
							if(blockNameTo != blockExist.attributes.name){
								positionExist.attributes.to = blockNameTo;							
							}													
							else{
								delete positionExist.attributes.to;
							}
						}
						else{
							positionExist = null;						
							rootLayout[0].children.each(function(blockChild, blockIdx){
								var childAttr = blockChild.attributes;								
								blockChild.children.each(function(positionChild, positionChildIdx){
									var positionChildAttr = positionChild.attributes;
									if(positionName.toLowerCase() == positionChildAttr.name.toLowerCase()){									
										positionExist = positionChild;
										positionIndex = positionChildIdx;								
										blockExist = blockChild;									
									}
								});
							});
							if(positionExist){								
								var positionLen = blockObj.getElements('.position').length;
								blockObj.getElements('.position').each(function(tmpItem, tmpIndex){
									if(tmpItem.id.replace('p-', '').toLowerCase() == positionName.toLowerCase()){
										if(tmpIndex == 0){
											positionExist.attributes.where = '';
										}
										else if(tmpIndex == positionLen - 1){
											delete positionExist.attributes.where;
										}
										else{
											positionExist.attributes.where = tmpItem.getPrevious().id.replace('p-', '');
										}										
									}									
								});	
								if(blockNameTo != blockExist.attributes.name){
									positionExist.attributes.to = blockNameTo;							
								}													
								else{
									delete positionExist.attributes.to;
								}
							}	
							else{	
								var newIndex = blockExist.children.length;
								blockExist.children[newIndex] = {
									tag: 'tmpl',
									attributes: {
										name: positionName,
										to: blockNameTo
									},
									children: []
								};
								
								var positionLen = blockObj.getElements('.position').length;
								blockObj.getElements('.position').each(function(tmpItem, tmpIndex){
									if(tmpItem.id.replace('p-', '').toLowerCase() == positionName.toLowerCase()){									
										if(tmpIndex == 0){
											blockExist.children[newIndex].attributes.where = '';
										}
										else if(tmpIndex == positionLen - 1){
											delete blockExist.children[newIndex].attributes.where;
										}
										else{
											blockExist.children[newIndex].attributes.where = tmpItem.getPrevious().id.replace('p-', '');
										}
									}									
								});	
								if(blockName == blockNameTo){
									delete blockExist.children[newIndex].attributes.to;
								}	
							}		
						}									
					}
					else{	
						positionExist = null;						
						rootLayout[0].children.each(function(blockChild, blockIdx){
							var childAttr = blockChild.attributes;								
							blockChild.children.each(function(positionChild, positionChildIdx){
								var positionChildAttr = positionChild.attributes;
								if(positionName.toLowerCase() == positionChildAttr.name.toLowerCase()){									
									positionExist = positionChild;
									positionIndex = positionChildIdx;								
									blockExist = blockChild;									
								}
							});
						});	
						if(positionExist){							
							var positionLen = blockObj.getElements('.position').length;
							blockObj.getElements('.position').each(function(tmpItem, tmpIndex){
								if(tmpItem.id.replace('p-', '').toLowerCase() == positionExist.attributes.name.toLowerCase()){
									if(tmpIndex == 0){
										positionExist.attributes.where = '';
									}
									else if(tmpIndex == positionLen - 1){
										delete positionExist.attributes.where;
									}
									else{
										positionExist.attributes.where = tmpItem.getPrevious().id.replace('p-', '');
									}										
								}									
							});																												
							if(blockNameTo != blockExist.attributes.name){
								positionExist.attributes.to = blockNameTo;							
							}													
							else{
								delete positionExist.attributes.to;
							}						
						}
						else{							
							var newIndex = rootLayout[0].children.length;
							rootLayout[0].children[newIndex] = {
								tag: 'tmpls',
								attributes: {
									name: blockName
								},
								children: []
							};								
							rootLayout[0].children[newIndex].children[0] = {
								tag: 'tmpl',
								attributes: {
									name: positionName,
									to: blockNameTo
								},
								children: []
							};	
														
							var positionLen = blockObj.getElements('.position').length;	
							blockObj.getElements('.position').each(function(tmpItem, tmpIndex){							
								if(tmpItem.id.replace('p-', '').toLowerCase() == positionName.toLowerCase()){
									if(tmpIndex == 0){
										rootLayout[0].children[newIndex].children[0].attributes.where = '';
									}
									else if(tmpIndex == positionLen - 1){
										delete rootLayout[0].children[newIndex].children[0].attributes.where;
									}
									else{
										rootLayout[0].children[newIndex].children[0].attributes.where = tmpItem.getPrevious().id.replace('p-', '');
									}
								}
							});
							if(blockName == blockNameTo){
								delete rootLayout[0].children[newIndex].children[0].attributes.to;
							}	
						}
					}
					rootLayout = optimizeGeneratedCode(rootLayout);
					$('paramslayoutsetting').value = JVXMLParser.hashesToHTML(rootLayout);					
					var retCoord = this.getCoordinates();
					new Fx.Styles(el, {
						duration: 500,	
						transition: Fx.Transitions.Quint.easeOut,
						wait: false,
						onComplete: function(){
							el.remove();
							jvDragging = false;		
						}
					}).start({top:retCoord.top, left:retCoord.left});				
				}
			});
		};		
		$$('.position, .position-placeholder').each(function(drop){
			addPositionDropEvents(drop);
		});
		
		function addBlockDropEvents(drop){
			drop.addEvents({
				'over': function(el, obj){								
					el.pr.inject(this, this.getPrevious().hasClass('block') ? 'after' : 'before');
					el.pr.addClass('draghover');
				},
				'drop': function(el, obj){	
					var groupObj = this.getParent();
					if(!el.ps.getParent().getElements('.block').length){
						addBlockDropEvents(el.ps.replaceWith(el.pr.clone(true).removeProperty('id').removeProperty('name').setHTML('[empty group]').addClass('block-placeholder')));
					}
					else{
						el.ps.remove();
					}
					if(el.pr.getParent().getElement('.block-placeholder')){
						el.pr.getParent().getElement('.block-placeholder').remove();
					}	
					el.pr.removeClass('draghover');					
					var groupNameTo = groupObj.id.replace('g-', '');
					var groupName = el.pr.getProperty('name');
					var blockName = el.id.replace('b-', '');
					var blockExist = null;
					var blockIndex = 0;
					rootLayout[0].children.each(function(blockChild, blockIdx){
						var childAttr = blockChild.attributes;
						if(blockName.toLowerCase() == childAttr.name.toLowerCase()){
							blockExist = blockChild;
							blockIndex = blockIdx;							
						}
					});							
					if(blockExist){
						var blockLen = groupObj.getElements('.block').length;						
						groupObj.getElements('.block').each(function(tmpItem, tmpIndex){
							if(tmpItem.id.replace('b-', '').toLowerCase() == blockName.toLowerCase()){
								if(tmpIndex == 0){
									blockExist.attributes.where = '';
								}
								else if(tmpIndex == blockLen - 1){
									delete blockExist.attributes.where;
								}
								else{
									blockExist.attributes.where = tmpItem.getPrevious().id.replace('b-', '');
								}
							}									
						});									
						blockExist.attributes.to = groupNameTo;
						if(blockExist.attributes.from){
							if(groupNameTo == blockExist.attributes.from){
								delete blockExist.attributes.to;
							}
						}
						else{
							blockExist.attributes.from = groupName;
							if(groupNameTo == groupName){								
								delete blockExist.attributes.to;
							}
						}
						if(blockExist.attributes.from == blockExist.attributes.to){
							delete blockExist.attributes.from;
							delete blockExist.attributes.to;
						}						
					}
					else{
						var newIndex = rootLayout[0].children.length;
						rootLayout[0].children[newIndex] = {
							tag: 'tmpls',
							attributes: {
								name: blockName,
								from: groupName,
								to: groupNameTo                                      
							},
							children: []
						};							
						var blockLen = groupObj.getElements('.block').length;
						groupObj.getElements('.block').each(function(tmpItem, tmpIndex){
							if(tmpItem.id.replace('b-', '').toLowerCase() == blockName.toLowerCase()){
								if(tmpIndex == 0){
									rootLayout[0].children[newIndex].attributes.where = '';
								}
								else if(tmpIndex == blockLen - 1){
									delete rootLayout[0].children[newIndex].attributes.where;
								}
								else{
									rootLayout[0].children[newIndex].attributes.where = tmpItem.getPrevious().id.replace('b-', '');
								}
							}									
						});	
						if(groupName == groupNameTo){
							delete rootLayout[0].children[newIndex].attributes.to;
						}	
					}	
					rootLayout = optimizeGeneratedCode(rootLayout);
					$('paramslayoutsetting').value = JVXMLParser.hashesToHTML(rootLayout);
				    var retCoord = this.getCoordinates();
					new Fx.Styles(el, {
						duration: 500,							
						transition: Fx.Transitions.Quint.easeOut,
						wait: false,
						onComplete: function(){
							el.remove();
							jvDragging = false;		
						}
					}).start({top:retCoord.top, left:retCoord.left});					
				}
			});
		};
		$$('.block, .block-placeholder').each(function(drop){
			addBlockDropEvents(drop);
		});
		 
		function optimizeGeneratedCode(rootLayout){
			rootLayout[0].children.each(function(blockChild, blockIdx){
				var blockAttr = blockChild.attributes;
				blockChild.children.each(function(positionChild, positionIdx){					
					var positionAttr = positionChild.attributes;
					var blockObj = $('b-' + blockAttr.name);
					var positionLen = blockObj.getElements('.position').length;
					blockObj.getElements('.position').each(function(tmpItem, tmpIndex){							
						if(tmpItem.id.replace('p-', '').toLowerCase() == positionAttr.name.toLowerCase()){
							if(tmpIndex == 0){
								positionChild.attributes.where = '';
							}
							else if(tmpIndex == positionLen - 1){
								delete positionChild.attributes.where;
							}
							else{
								positionChild.attributes.where = tmpItem.getPrevious().id.replace('p-', '');
							}
						}
					});
					if(positionChild.attributes.to && positionChild.attributes.to != ''){
						var blockObj2 = $('b-' + positionChild.attributes.to);
						var positionLen2 = blockObj2.getElements('.position').length;
						blockObj2.getElements('.position').each(function(tmpItem, tmpIndex){							
							if(tmpItem.id.replace('p-', '').toLowerCase() == positionAttr.name.toLowerCase()){
								if(tmpIndex == 0){
									positionChild.attributes.where = '';
								}
								else if(tmpIndex == positionLen2 - 1){
									delete positionChild.attributes.where;
								}
								else{
									positionChild.attributes.where = tmpItem.getPrevious().id.replace('p-', '');
								}
							}
						});
					}
				});
				
				var groupObj = $('g-' + blockChild.attributes.from);
				if(groupObj){
					var blockLen = groupObj.getElements('.block').length;
					groupObj.getElements('.block').each(function(tmpItem, tmpIndex){							
						if(tmpItem.id.replace('b-', '').toLowerCase() == blockAttr.name.toLowerCase()){
							if(tmpIndex == 0){
								blockChild.attributes.where = '';
							}
							else if(tmpIndex == blockLen - 1){
								delete blockChild.attributes.where;
							}
							else{
								blockChild.attributes.where = tmpItem.getPrevious().id.replace('b-', '');
							}
						}
					});				
				}
			});	
			return rootLayout;
		};
		 
        // icon toggle block
        $$('.icon-toggle-block').each(function(iconCollapse){
           iconCollapse.removeEvents('click').addEvent('click', function(e){
				new Event(e).stop();                
                this.getParent().getParent().getParent().toggleClass('collapse'); 
                this.getParent().getParent().getParent().getElements('.position').toggleClass('hidden');
                if(this.getParent().getParent().getParent().hasClass('collapse')){
                    this.setProperty('title', this.getProperty('title').replace('Collapse', 'Expand'));
                }else{
                    this.setProperty('title', this.getProperty('title').replace('Expand', 'Collapse'));
                }
           });
        });
		// icon toggle group
		$$('.icon-toggle-group').each(function(iconCollapse){
           iconCollapse.removeEvents('click').addEvent('click', function(e){
				new Event(e).stop();                
                this.getParent().getParent().getParent().toggleClass('collapse'); 
                this.getParent().getParent().getParent().getElements('.block').toggleClass('hidden');
                if(this.getParent().getParent().getParent().hasClass('collapse')){
                    this.setProperty('title', this.getProperty('title').replace('Collapse', 'Expand'));
                }else{
                    this.setProperty('title', this.getProperty('title').replace('Expand', 'Collapse'));
                }
           });
        });
         // icon add block
        $$('.icon-add-block').each(function(iconAddBlock){
           iconAddBlock.removeEvents().addEvent('click', function(e){
                new Event(e).stop();
                var groupName = this.getParentByClass('group').id.replace('g-', '');
                var paramsLayer = new Element('div', {
                   'class': 'paramsLayer' 
                });
                var paramsData = '<form action="" name="paramsForm" id="paramsForm" onsubmit="return jvAdmin.addBlock(\'' + groupName + '\');"><fieldset class="paramsform"><legend>&nbsp;&nbsp;&nbsp;Add Block</legend><table class="admintable">';
                paramsData += '<tr><td class="key">Name:</td><td><input type="text" name="pfName" id="pfName" class="wid200" /></td></tr>';
                paramsData += '<tr><td class="key">Id:</td><td><input type="text" name="pfId" id="pfId" class="wid200" /></td></tr>';
                paramsData += '<tr><td class="key">Inner:</td><td><input type="text" name="pfInner" id="pfInner" class="wid200" /></td></tr>';
                paramsData += '<tr><td class="key">Class:</td><td><input type="text" name="pfClass" id="pfClass" class="wid200" /></td></tr>';
                paramsData += '<tr><td class="key">Always Show:</td><td><select name="pfAlwaysShow" id="pfAlwaysShow" class="wid200"><option value="">- default -</option><option value="true">True</option><option value="false">False</option></td></tr>';
                paramsData += '<tr><td class="key">Equal:</td><td><select name="pfEqual" id="pfEqual" class="wid200"><option value="">- default -</option><option value="height">Height</option><option value="width">Width</option><option value="both">Both</option></td></tr>';
                paramsData += '<tr><td class="key" colspan="2" align="center"><input type="reset" name="pfReset" id="pfReset" value="Reset" />&nbsp;<input type="submit" name="pfSubmit" id="pfSubmit" value="Save" /></td></tr>';
                paramsData += '</table></fieldset></form>';               
                paramsLayer.setHTML(paramsData);
                SqueezeBox.fromElement(paramsLayer, {
                    handler: 'adopt',
                    size: {x: 400, y: 240}               
                });
           });
        });
        // icon edit block
        $$('.icon-edit-block').each(function(iconEditBlock){
           iconEditBlock.removeEvents().addEvent('click', function(e){
                new Event(e).stop();
                var groupName = this.getParentByClass('group').id.replace('g-', '');
                var paramsLayer = new Element('div', {
                   'class': 'paramsLayer' 
                });
                var pfName = '', pfId = '', pfInner = '', pfClass = '', pfAlwaysShow = '', pfEqual = '';
                var jsData = new Hash(Json.evaluate(this.getParent().getParent().getProperty('props')));
                jsData.each(function(value, key){
                   if(key == 'name'){
                        pfName = value;     
                   }
                   if(key == 'id'){
                        pfId = value;
                   }
                   if(key == 'inner'){
                        pfInner = value;
                   }
                   if(key == 'class'){
                        pfClass = value;
                   }                   
                   if(key == 'alwaysshow'){
                        pfAlwaysShow = value;
                   }
                   if(key == 'equal'){
                        pfEqual = value;
                   }
                }); 				
				var positionWhere = '_top_';
				var groupObj = this.getParentByClass('group');
				var positionLen = groupObj.getElements('.block').length;
				groupObj.getElements('.block').each(function(tmpItem, tmpIndex){
					if(tmpItem.id.replace('b-', '').toLowerCase() == pfName.toLowerCase()){
						if(tmpIndex == 0){
							positionWhere = '_top_';
						}
						else if(tmpIndex == positionLen - 1){
							positionWhere = '_bottom_';
						}
						else{
							positionWhere = tmpItem.getPrevious().id.replace('b-', '');
						}										
					}									
				});	
                var paramsData = '<form action="" name="paramsForm" id="paramsForm" onsubmit="return jvAdmin.addBlock(\'' + groupName + '\',\'' + positionWhere + '\');"><fieldset class="paramsform"><legend>&nbsp;&nbsp;&nbsp;Edit Block</legend><table class="admintable">';
                paramsData += '<tr><td class="key">Name:</td><td><input type="text" name="pfName" id="pfName" class="wid200" value="'+ pfName +'" /></td></tr>';
                paramsData += '<tr><td class="key">Id:</td><td><input type="text" name="pfId" id="pfId" class="wid200" value="'+ pfId +'" /></td></tr>';
                paramsData += '<tr><td class="key">Inner:</td><td><input type="text" name="pfInner" id="pfInner" class="wid200" value="'+ pfInner +'" /></td></tr>';
                paramsData += '<tr><td class="key">Class:</td><td><input type="text" name="pfClass" id="pfClass" class="wid200" value="'+ pfClass +'" /></td></tr>';
                paramsData += '<tr><td class="key">Always Show:</td><td><select name="pfAlwaysShow" id="pfAlwaysShow" class="wid200"><option value="">- default -</option>';
                var tmp = '';
                if(pfAlwaysShow.toLowerCase() == 'true'){ tmp = ' selected="selected"';} paramsData += '<option value="true"'+ tmp + '>true</option>'; tmp = '';
                if(pfAlwaysShow.toLowerCase() == 'false'){ tmp = ' selected="selected"';} paramsData += '<option value="false"'+ tmp + '>false</option></td></tr>'; tmp = '';
                paramsData += '<tr><td class="key">Equal:</td><td><select name="pfEqual" id="pfEqual" class="wid200"><option value="false">- default -</option>';
                if(pfEqual.toLowerCase() == 'height'){ tmp = ' selected="selected"';} paramsData += '<option value="height"'+ tmp + '>height</option>'; tmp = '';
                if(pfEqual.toLowerCase() == 'width'){ tmp = ' selected="selected"';} paramsData += '<option value="width"'+ tmp + '>width</option>'; tmp = '';
                if(pfEqual.toLowerCase() == 'both'){ tmp = ' selected="selected"';} paramsData += '<option value="both"'+ tmp + '>both</option></td></tr>'; tmp = '';
                paramsData += '<tr><td class="key" colspan="2" align="center"><input type="reset" name="pfReset" id="pfReset" value="Reset" />&nbsp;<input type="submit" name="pfSubmit" id="pfSubmit" value="Save" /></td></tr>';
                paramsData += '</table></fieldset></form>';               
                paramsLayer.setHTML(paramsData);
                SqueezeBox.fromElement(paramsLayer, {
                    handler: 'adopt',
                    size: {x: 400, y: 240}               
                });
           });
        });
        // icon delete block
        $$('.icon-delete-block').each(function(iconDeleteBlock){
           iconDeleteBlock.removeEvents().addEvent('click', function(e){
                new Event(e).stop();
                var groupName = this.getParentByClass('group').id.replace('g-', '');
                var blockName = this.getParentByClass('block').id.replace('b-', '');
                var paramsLayer = new Element('div', {
                   'class': 'paramsLayer' 
                });              
                var paramsData = '<form action="" name="paramsForm" id="paramsForm" onsubmit="return jvAdmin.deleteBlock(\'' + groupName + '\',\'' + blockName + '\');"><fieldset class="paramsform"><legend>&nbsp;&nbsp;&nbsp;Delete Block</legend><table class="admintable">';
                paramsData += '<tr><td colspan="2" align="center">Are you sure you want to delete this block?</td></tr>';
                paramsData += '<tr><td class="key" colspan="2" align="center"><input type="reset" name="pfNo" id="pfNo" value="No" onclick="SqueezeBox.listeners.close();return false;"/>&nbsp;<input type="submit" name="pfSubmit" id="pfSubmit" value="Yes" /></td></tr>';
                paramsData += '</table></fieldset></form>';               
                paramsLayer.setHTML(paramsData);
                SqueezeBox.fromElement(paramsLayer, {
                    handler: 'adopt',
                    size: {x: 400, y: 120}               
                });
           });
        });
        // icon add position
        $$('.icon-add-position').each(function(iconAddPosition){
           iconAddPosition.removeEvents().addEvent('click', function(e){
                new Event(e).stop();                
                var blockName = this.getParentByClass('block').id.replace('b-', '');
                var paramsLayer = new Element('div', {
                   'class': 'paramsLayer' 
                });
                var paramsData = '<form action="" name="paramsForm" id="paramsForm" onsubmit="return jvAdmin.addPosition(\'' + blockName + '\');"><fieldset class="paramsform"><legend>&nbsp;&nbsp;&nbsp;Add Position</legend><table class="admintable">';
                paramsData += '<tr><td class="key">Name:</td><td><input type="text" name="pfName" id="pfName" class="wid200" /></td></tr>';                
                paramsData += '<tr><td class="key">Type:</td><td><select name="pfType" id="pfType" class="wid200"><option value="modules">Modules</option><option value="component">Component</option></td></tr>';
                paramsData += '<tr><td class="key">Style:</td><td><select name="pfStyle" id="pfStyle" class="wid200"><option value="">- default -</option><option value="none">none</option><option value="table">table</option><option value="horz">horz</option><option value="xhtml">xhtml</option><option value="outline">outline</option><option value="rounded">rounded</option><option value="custom">custom</option><option value="jvxhtml">jvxhtml</option><option value="jvxhtmls">jvxhtmls</option></tr>';
                paramsData += '<tr><td class="key">Class:</td><td><input type="text" name="pfClass" id="pfClass" class="wid200" /></td></tr>';
                paramsData += '<tr><td class="key">Inner:</td><td><input type="text" name="pfInner" id="pfInner" class="wid200" /></td></tr>';
                paramsData += '<tr><td class="key">Width:</td><td><input type="text" name="pfWidth" id="pfWidth" class="wid200" /></td></tr>';
                paramsData += '<tr><td class="key"  colspan="2" align="center"><input type="reset" name="pfReset" id="pfReset" value="Reset" />&nbsp;<input type="submit" name="pfSubmit" id="pfSubmit" value="Save" /></td></tr>';
                paramsData += '</table></fieldset></form>';               
                paramsLayer.setHTML(paramsData);
                SqueezeBox.fromElement(paramsLayer, {
                    handler: 'adopt',
                    size: {x: 400, y: 240}
                });
           });
           
        });
        // icon edit position
        $$('.icon-edit-position').each(function(iconEditPosition){
           iconEditPosition.removeEvents().addEvent('click', function(e){
                new Event(e).stop();
                var blockName = this.getParentByClass('block').id.replace('b-', '');
                var paramsLayer = new Element('div', {
                   'class': 'paramsLayer' 
                });
                var pfName = '', pfType = '', pfStyle = '', pfClass = '', pfInner = '', pfWidth = '';
                var jsData = new Hash(Json.evaluate(this.getParent().getParent().getProperty('props')));
                jsData.each(function(value, key){
                   if(key == 'name'){
                        pfName = value;     
                   }
                   if(key == 'type'){
                        pfType = value;
                   }
                   if(key == 'style'){
                        pfStyle = value;
                   }
                   if(key == 'class'){
                        pfClass = value;
                   }
                   if(key == 'inner'){
                        pfInner = value;
                   }
                   if(key == 'width'){
                        pfWidth = value;
                   }
                }); 
				var positionWhere = '_top_';
				var blockObj = this.getParentByClass('block');
				var positionLen = blockObj.getElements('.position').length;
				blockObj.getElements('.position').each(function(tmpItem, tmpIndex){
					if(tmpItem.id.replace('p-', '').toLowerCase() == pfName.toLowerCase()){
						if(tmpIndex == 0){
							positionWhere = '_top_';
						}
						else if(tmpIndex == positionLen - 1){
							positionWhere = '_bottom_';
						}
						else{
							positionWhere = tmpItem.getPrevious().id.replace('p-', '');
						}										
					}									
				});	
				var paramsData = '<form action="" name="paramsForm" id="paramsForm" onsubmit="return jvAdmin.addPosition(\'' + blockName + '\',\'' + positionWhere + '\');"><fieldset class="paramsform"><legend>&nbsp;&nbsp;&nbsp;Edit Position</legend><table class="admintable">';
                paramsData += '<tr><td class="key">Name:</td><td><input type="text" name="pfName" id="pfName" class="wid200" value="'+ pfName +'"/></td></tr>';                
                paramsData += '<tr><td class="key">Type:</td><td><select name="pfType" id="pfType" class="wid200">';
                var tmp = '';
                if(pfType.toLowerCase() == 'modules'){ tmp = ' selected="selected"';} paramsData += '<option value="modules"'+ tmp + '>modules</option>'; tmp = '';
                if(pfType.toLowerCase() == 'component'){ tmp = ' selected="selected"';} paramsData += '<option value="component"'+ tmp + '>component</option></td></tr>'; tmp = '';                
                paramsData += '<tr><td class="key">Style:</td><td><select name="pfStyle" id="pfStyle" class="wid200"><option value="">- default -</option>';                
                if(pfStyle.toLowerCase() == 'none'){ tmp = ' selected="selected"';} paramsData += '<option value="none"'+ tmp + '>none</option>'; tmp = '';
                if(pfStyle.toLowerCase() == 'table'){ tmp = ' selected="selected"';} paramsData += '<option value="table"'+ tmp + '>table</option>'; tmp = '';
                if(pfStyle.toLowerCase() == 'horz'){ tmp = ' selected="selected"';} paramsData += '<option value="horz"'+ tmp + '>horz</option>'; tmp = '';
                if(pfStyle.toLowerCase() == 'xhtml'){ tmp = ' selected="selected"';} paramsData += '<option value="xhtml"'+ tmp + '>xhtml</option>'; tmp = '';
                if(pfStyle.toLowerCase() == 'outline'){ tmp = ' selected="selected"';} paramsData += '<option value="outline"'+ tmp + '>outline</option>'; tmp = '';
                if(pfStyle.toLowerCase() == 'rounded'){ tmp = ' selected="selected"';} paramsData += '<option value="rounded"'+ tmp + '>rounded</option>'; tmp = '';
                if(pfStyle.toLowerCase() == 'custom'){ tmp = ' selected="selected"';} paramsData += '<option value="custom"'+ tmp + '>custom</option>'; tmp = '';
                if(pfStyle.toLowerCase() == 'jvxhtml'){ tmp = ' selected="selected"';} paramsData += '<option value="jvxhtml"'+ tmp + '>jvxhtml</option>'; tmp = '';
                if(pfStyle.toLowerCase() == 'jvxhtmls'){ tmp = ' selected="selected"';} paramsData += '<option value="jvxhtmls"'+ tmp + '>jvxhtmls</option>'; tmp = '';
                paramsData += '<tr><td class="key">Class:</td><td><input type="text" name="pfClass" id="pfClass" class="wid200" value="'+ pfClass +'"/></td></tr>';
                paramsData += '<tr><td class="key">Inner:</td><td><input type="text" name="pfInner" id="pfInner" class="wid200" value="'+ pfInner +'"/></td></tr>';
                paramsData += '<tr><td class="key">Width:</td><td><input type="text" name="pfWidth" id="pfWidth" class="wid200" value="'+ pfWidth +'"/></td></tr>';
                paramsData += '<tr><td class="key" colspan="2" align="center"><input type="reset" name="pfReset" id="pfReset" value="Reset"/>&nbsp;<input type="submit" name="pfSubmit" id="pfSubmit" value="Save" /></td></tr>';
                paramsData += '</table></fieldset></form>';               
                paramsLayer.setHTML(paramsData);
                SqueezeBox.fromElement(paramsLayer, {
                    handler: 'adopt',
                    size: {x: 400, y: 240}
                });
           });
        });
        // icon delete position
        $$('.icon-delete-position').each(function(iconDeletePosition){
            iconDeletePosition.removeEvents().addEvent('click', function(e){
                new Event(e).stop();
                var blockName = this.getParentByClass('block').id.replace('b-', '');                
				var positionName = this.getParentByClass('position').id.replace('p-', '');
                var paramsLayer = new Element('div', {
                   'class': 'paramsLayer' 
                });              
                var paramsData = '<form action="" name="paramsForm" id="paramsForm" onsubmit="return jvAdmin.deletePosition(\'' + blockName + '\',\'' + positionName + '\');"><fieldset class="paramsform"><legend>&nbsp;&nbsp;&nbsp;Delete Position</legend><table class="admintable">';
                paramsData += '<tr><td colspan="2" align="center">Are you sure you want to delete this position?</td></tr>';
                paramsData += '<tr><td class="key" colspan="2" align="center"><input type="reset" name="pfNo" id="pfNo" value="No" onclick="SqueezeBox.listeners.close();return false;"/>&nbsp;<input type="submit" name="pfSubmit" id="pfSubmit" value="Yes" /></td></tr>';
                paramsData += '</table></fieldset></form>';               
                paramsLayer.setHTML(paramsData);
                SqueezeBox.fromElement(paramsLayer, {
                    handler: 'adopt',
                    size: {x: 400, y: 120}               
                });
           });
        });
	},
    addPosition: function(blockName, where){
        var paramsForm = $('paramsForm');
        if(!paramsForm) return true;        
		var positionName = paramsForm.getElement('input[name=pfName]').value.trim();  
        if(positionName == ''){
            alert('Please enter position name');
            return false;
        }      
        var positionType = paramsForm.getElement('select[name=pfType]').value.trim();   
        var positionStyle = paramsForm.getElement('select[name=pfStyle]').value.trim();             
        var positionClass = paramsForm.getElement('input[name=pfClass]').value.trim();
        var positionInner = paramsForm.getElement('input[name=pfInner]').value.trim();
        var positionWidth = paramsForm.getElement('input[name=pfWidth]').value.trim();
        
        var blockExist = null, positionExist = null, positionIndex = 0;
		rootLayout[0].children.each(function(blockChild){
			var childAtt = blockChild.attributes;
			if(blockName.toLowerCase() == childAtt.name.toLowerCase()){
				blockExist = blockChild;																
			}
		});				
		if(blockExist){							
			blockExist.children.each(function(positionChild, index){
				var childAtt = positionChild.attributes;                  
				if(positionName.toLowerCase() == childAtt.name.toLowerCase()){
					positionExist = positionChild;
					positionIndex = index;
					return;
				}
			});
          
			if(positionExist){
			    if(positionType != ''){
			         positionExist.attributes.type =  positionType;
			    } 
                else{
                    delete positionExist.attributes.type;
                }
                if(positionStyle != ''){
			         positionExist.attributes.style =  positionStyle;
			    }
                else{
                    delete positionExist.attributes.style;
                }
                if(positionClass != ''){
			         positionExist.attributes['class'] = positionClass;
			    }
                else{
                    delete positionExist.attributes['class'];
                }
                if(positionInner != ''){
			         positionExist.attributes.inner =  positionInner;
			    }
                else{
                    delete positionExist.attributes.inner;
                }
                if(positionWidth != ''){
			         positionExist.attributes.width =  positionWidth;
			    }
                else{
                    delete positionExist.attributes.width;
                }
				if(where){
					if(where == '_top_'){
						positionExist.attributes.where = '';
					}
					else if(where == '_bottom_'){
						delete positionExist.attributes.where;
					}
					else{
						positionExist.attributes.where = where;
					}				
				}				
			}
			else{													
				blockExist.children[blockExist.children.length] = {
					tag: 'tmpl',
					attributes: {
    					name: positionName                        
					},
					children: []
				};
                if(positionType != ''){
   	                blockExist.children[blockExist.children.length - 1].attributes.type =  positionType;
			    } 
                if(positionStyle != ''){
			        blockExist.children[blockExist.children.length - 1].attributes.style =  positionStyle;
			    }
                if(positionClass != ''){
			        blockExist.children[blockExist.children.length - 1].attributes['class'] =  positionClass;
			    }
                if(positionInner != ''){
			         blockExist.children[blockExist.children.length - 1].attributes.inner =  positionInner;
			    }
                if(positionWidth != ''){
			        blockExist.children[blockExist.children.length - 1].attributes.width =  positionWidth;
			    }
				if(where){
					if(where == '_top_'){
						blockExist.children[blockExist.children.length - 1].attributes.where = '';
					}
					else if(where == '_bottom_'){
						delete blockExist.children[blockExist.children.length - 1].attributes.where;
					}
					else{
						blockExist.children[blockExist.children.length - 1].attributes.where = where;
					}
				}
			}
        }	
        else{
			rootLayout[0].children[rootLayout[0].children.length] = {
				tag: 'tmpls',
				attributes: {
					name: blockName
				},
				children: []
			};								
			rootLayout[0].children[rootLayout[0].children.length - 1].children[0] = {
				tag: 'tmpl',
				attributes: {
					name: positionName
				},
				children: []
			};  
            if(positionType != ''){
                rootLayout[0].children[rootLayout[0].children.length - 1].children[0].attributes.type =  positionType;
		    } 
            if(positionStyle != ''){
		        rootLayout[0].children[rootLayout[0].children.length - 1].children[0].attributes.style =  positionStyle;
		    }
            if(positionClass != ''){
		      rootLayout[0].children[rootLayout[0].children.length - 1].children[0].attributes['class'] =  positionClass;
		    }
            if(positionInner != ''){
		        rootLayout[0].children[rootLayout[0].children.length - 1].children[0].attributes.inner =  positionInner;
		    }
            if(positionWidth != ''){
		       rootLayout[0].children[rootLayout[0].children.length - 1].children[0].attributes.width =  positionWidth;
		    }  
			if(where){
				if(where == '_top_'){
					rootLayout[0].children[rootLayout[0].children.length - 1].children[0].attributes.where = '';
				}
				else if(where == '_bottom_'){
					delete rootLayout[0].children[rootLayout[0].children.length - 1].children[0].attributes.where;
				}
				else{
					rootLayout[0].children[rootLayout[0].children.length - 1].children[0].attributes.where = where;
				}       		
			}
		}	
		$('paramslayoutsetting').value = JVXMLParser.hashesToHTML(rootLayout);
        submitbutton('apply');
        return false;  
    }, 
    deletePosition: function(blockName, positionName){
        var blockExist = null, positionExist = null, positionIndex = 0;
		rootLayout[0].children.each(function(blockChild){
			var childAtt = blockChild.attributes;			
			blockChild.children.each(function(positionChild, index){
				var childAtt = positionChild.attributes;                  
				if(positionName.toLowerCase() == childAtt.name.toLowerCase()){
					positionExist = positionChild;
					return;				
				}
			});
			if(blockName.toLowerCase() == childAtt.name.toLowerCase()){
				blockExist = blockChild;	
				return;					
			}
		});				
		if(positionExist || blockExist){							
			if(positionExist){
			    positionExist.attributes.hidden =  true;			    
			}
			else if(blockExist){													
				blockExist.children[blockExist.children.length] = {
					tag: 'tmpl',
					attributes: {
    					name: positionName                        
					},
					children: []
				};
                blockExist.children[blockExist.children.length - 1].attributes.hidden =  true;			    
			}
        }	
        else{
			rootLayout[0].children[rootLayout[0].children.length] = {
				tag: 'tmpls',
				attributes: {
					name: blockName
				},
				children: []
			};								
			rootLayout[0].children[rootLayout[0].children.length - 1].children[0] = {
				tag: 'tmpl',
				attributes: {
					name: positionName
				},
				children: []
			};  
            rootLayout[0].children[rootLayout[0].children.length - 1].children[0].attributes.hidden =  true;		           		
		}	
		$('paramslayoutsetting').value = JVXMLParser.hashesToHTML(rootLayout);
        submitbutton('apply');
        return false;  
    },   
    addBlock: function(groupName, where){
        var paramsForm = $('paramsForm');
        if(!paramsForm) return true;        
		var blockName = paramsForm.getElement('input[name=pfName]').value.trim();  
        if(blockName == ''){
            alert('Please enter block name');
            return false;
        }      
        var blockId = paramsForm.getElement('input[name=pfId]').value.trim();        
        var blockInner = paramsForm.getElement('input[name=pfInner]').value.trim();           
        var blockClass = paramsForm.getElement('input[name=pfClass]').value.trim();
        var blockAlwaysShow = paramsForm.getElement('select[name=pfAlwaysShow]').value.trim();
        var blockEqual = paramsForm.getElement('select[name=pfEqual]').value.trim();
        
        var blockExist = null;
		rootLayout[0].children.each(function(blockChild){
			var childAtt = blockChild.attributes;
			if(blockName.toLowerCase() == childAtt.name.toLowerCase()){
				blockExist = blockChild;
				return;							
			}
		});					
		if(blockExist){	
			blockExist.attributes.from = groupName;
            if(blockInner != ''){
                blockExist.attributes.inner = blockInner;
            }
            else{
                delete blockExist.attributes.inner;
            }            
            if(blockClass != ''){
                blockExist.attributes['class'] = blockClass;
            }
            else{
                delete blockExist.attributes['class'];
            }
            if(blockAlwaysShow != ''){
                blockExist.attributes.alwaysShow = blockAlwaysShow;
            }
            else{
                delete blockExist.attributes.alwaysShow;
            }
            if(blockEqual != ''){
                blockExist.attributes.equal = blockEqual;
            }           					
            else{
                delete blockExist.attributes.equal;
            }
			if(where){
				if(where == '_top_'){
					blockExist.attributes.where = '';
				}
				else if(where == '_bottom_'){
					delete blockExist.attributes.where;
				}
				else{
					blockExist.attributes.where = where;
				}				
			}	
		}
		else{
			rootLayout[0].children[rootLayout[0].children.length] = {
				tag: 'tmpls',
				attributes: {
					from: groupName,
                    name: blockName                    
				},
				children: []
			};
            if(blockId != ''){
               rootLayout[0].children[rootLayout[0].children.length - 1].attributes.id = blockId;              
            }
            if(blockInner != ''){
               rootLayout[0].children[rootLayout[0].children.length - 1].attributes.inner = blockInner;              
            }
            if(blockClass != ''){
               rootLayout[0].children[rootLayout[0].children.length - 1].attributes['class'] = blockClass;              
            }
            if(blockAlwaysShow != ''){
               rootLayout[0].children[rootLayout[0].children.length - 1].attributes.alwaysShow = blockAlwaysShow;              
            }
            if(blockEqual != ''){
               rootLayout[0].children[rootLayout[0].children.length - 1].attributes.equal = blockEqual;              
            }
            if(where){
				if(where == '_top_'){
					rootLayout[0].children[rootLayout[0].children.length - 1].attributes.where = '';
				}
				else if(where == '_bottom_'){
					delete rootLayout[0].children[rootLayout[0].children.length - 1].attributes.where;
				}
				else{
					rootLayout[0].children[rootLayout[0].children.length - 1].attributes.where = where;
				}				
			}	
		}	
		$('paramslayoutsetting').value = JVXMLParser.hashesToHTML(rootLayout);
        submitbutton('apply');
        return false;  
    },
    deleteBlock: function(groupName, blockName){
        var blockExist = null;
		rootLayout[0].children.each(function(blockChild){
			var childAtt = blockChild.attributes;
			if(blockName.toLowerCase() == childAtt.name.toLowerCase()){
				blockExist = blockChild;
				return;							
			}
		});					
		if(blockExist){	
			blockExist.attributes.hidden = true;
		}
		else{
			rootLayout[0].children[rootLayout[0].children.length] = {
				tag: 'tmpls',
				attributes: {
					from: groupName,
                    name: blockName,
                    hidden: true                    
				},
				children: []
			};
		}	
		$('paramslayoutsetting').value = JVXMLParser.hashesToHTML(rootLayout);
        submitbutton('apply');
        return false;         
    },
	resetLayout: function(){
		var layout = $('paramslayoutsetting');
		var answer = confirm('Do you want to reset to default?');
		if(answer){
			layout.value = '';
			submitbutton('apply');
		}
	},
	loadLayout: function(url){
		var layout = $('choose-layout');
		var l = layout.value;                        
		if(l != -1){		  
            $('layoutname').value = l;
			submitbutton('loadlayout');			
		} 
		else{
			alert('Please select a layout!');
		}
	},
	saveLayout: function(){
		var ret = window.prompt('please enter custom layout name:');
		if(ret && ret.trim() != ''){
		    $('layoutname').value = ret;
            submitbutton('savelayout');		
		}
	},
	deleteLayout: function(){
		var layout = $('choose-layout');
		var l = layout.value;                        
		if(l != -1){
			var answer = confirm('Do you want to delete selected layout?');
			if(answer){
                $('layoutname').value = l;
				submitbutton('deletelayout');		
			}		
		} 
		else{
			alert('Please select a layout!');
		}		
	},
    clearCache: function(type){
		var answer = confirm('Do you want to clear cache ?');
		if(answer){		    
		    $('cachetype').value = type;
			submitbutton('clear');
		}
	},
    checkAllTheme: function(element){
		var selectEl = $(element);
		for(var i = 0, len = selectEl.options.length; i < len; i++){
			selectEl.options[i].selected = true;
		}
		selectEl.disabled = false;		
	},
	checkNoneTheme: function(element){
		var selectEl = $(element);
		for(var i = 0, len = selectEl.options.length; i < len; i++){
			selectEl.options[i].selected = false;
		}
		selectEl.disabled = true;
	},
	checkTheme: function(element){
		var selectEl = $(element);
		selectEl.disabled = false;
		for(var i = 0, len = selectEl.options.length; i < len; i++){
			selectEl.options[i].disabled = false;			
		}
	},    
    
    update: function(version){        
        var loading = new Element('div', {'id': 'loading'}).injectInside($$('body')[0]);
        var overlay = new Element('div', {'id': 'overlay'}).injectInside($$('body')[0]).setStyle('opacity', 0.5);    
        var step    = new Element('div', {'id': 'step'}).injectInside(loading).setText('Waiting for update ....'); 
        
        new Json.Remote($('updateUrl').value+'&task=checkupdate', { 		
            onRequest: function(){ 
				step.setText('Get update link..');
			},
            
    		onComplete: function(res){
    		  
    		  new Ajax('index.php?option=com_jvframework&c=update', {
            		method: 'post',
            		data: {
            			task: 'update',
            			version: res.version,
                        url: res.updateurl,
                        name: res.package,
                        current: version				
            		},
                    
                    onRequest: function(){ 
        				step.setText('Downloading package..');
        			},
                    
            		onComplete: function(res){
                        step.setText('Update successfully...');
                                 
                        setTimeout(function(){
                            step.remove();
                            loading.remove();
                            overlay.remove();
                            window.location = window.location;
                       }, 1000);
            		}
              }).request(); 
    		}
    	}).send();
    },
    
    updateBasetheme: function(){
        new Ajax($('updateUrl').value, {
    		method: 'post',
    		data: {
    			task: 'updateBasetheme'
    		},
    		onComplete: function(res){
                 SqueezeBox.listeners.close();  
                 if(res == 1){
                    //submitbutton('complete');    
                 } else {
                    //submitbutton('error');   
                 }
    		}
      }).request(); 
    },
    
    editLayoutFile: function (){
        var filelist = $('fileList');
		var l = filelist.value;     
        var theme = document.adminForm.theme.value;    
        var status = $('editor-status');                             
		if(l != -1){		  
           new Ajax('index.php?option=com_jvframework&task=loadfile', {
    		method: 'post',
    		data: {
    			file: l,
                theme:theme		
    		},
    		onComplete: function(res){
    		      if(res == 'Error'){
    		          status.removeClass('success');
        		      status.addClass('error');
        		      status.setHTML('Error when trying to read file, please check file permission !!');
                      alert('Error when trying to read file, please check file permission !!');
        		  } else {
        		      
                      var filetype = l.split('|')[1];
                      switch(filetype){
                        case 'js':
                            editor.setParser('JSParser');   
                            break;
                        case 'css':
                            editor.setParser('CSSParser');   
                            break;    
                        case 'layouts':
                        case 'root':
                            editor.setParser('XMLParser');   
                            break;  
                        default:
                            editor.setParser('HTMLMixedParser');     
                      }
        		      
                      editor.setCode(res);
                      status.removeClass('error');                      
        		      status.addClass('success');
        		      status.setHTML('File loaded!');
        		  }
                
    		}
          }).request(); 
           
		} 
		else{
		   editor.setCode('');
		}
    },
    
    saveLayoutFile: function (){
        var editedCode = editor.getCode();
        var filelist = $('fileList');
		var l = filelist.value; 
        var theme = document.adminForm.theme.value; 
        var status = $('editor-status');                  
        if(l != -1){	
            new Ajax('index.php?option=com_jvframework&task=savefile', {
        		method: 'post',                
        		data: {
        			file: l,
                    code:editedCode,	
                    theme:theme	
        		},
                onStart: function(e){
                    alert(1)
                },
        		onComplete: function(res){
        		  if(res == 'Error'){
        		      status.removeClass('success');
        		      status.addClass('error');
        		      status.setHTML('Error when trying to save file, please check file permission !!');
                      alert('Error when trying to save file, please check file permission !!');
        		  } else {
        		      status.removeClass('error');
        		      status.addClass('success');
        		      status.setHTML('File Saved!');
                      alert('File Saved!');
        		  }
        		}
              }).request();   
          }   
                        
    }
    
});
JVAdmin.implement(new Options);


/*
	init functions here
*/
window.addEvent('domready', function() {
	jvAdmin = new JVAdmin();
});